import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/util/DbUtil.dart';

import '../../../data/StaticData.dart';
import '../../dao/ImSessionDao.dart';
import '../../pojo/ImPojo.dart';
import '../../util/ImConstant.dart';
import '../../util/ImSingleton.dart';
import '../bloc/SessionListCubit.dart';
import '../view/ListSeparator.dart';
import '../view/component/UserIconView.dart';
import '../view/component/dialog/DefaultDialog.dart';
import '../view/component/dialog/VideoAndAudioBottomSheet.dart';

/// 主页-》通信率-》用户
class UserInfoPage extends StatelessWidget {
  final ImUser user;

  const UserInfoPage({required this.user, super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      body: Column(children: [
        _buildTitle(),

        Expanded(child: Material(color: ImConstant.IM_RESERVE_BACKGROUND_COLOR, child: Column(
          children: [
            ListSeparator(
              indent: 10,
            ),
            _buildUserSetting(),
            Container(
              color: ImConstant.IM_MAIN_BACKGROUND_COLOR,
              height: 5,
            ),
            _buildSendMessagePane(context),
            ListSeparator(
              indent: 10,
            ),
            _buildSendAudioPane(context),

            Expanded(child: Container(color: ImConstant.IM_MAIN_BACKGROUND_COLOR,))
          ],
        ),), )

      ],),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
      leading: IconButton(
        icon: const Icon(Icons.chevron_left, color: Main_appbar_text_color),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: [
        IconButton(onPressed: () {}, icon: const Icon(Icons.more_horiz)),
      ],
    );
  }

  Widget _buildTitle() {
    return Container(
      color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
      padding: const EdgeInsets.only(left: 10, right: 10, bottom: 5),
      child: Row(
        children: [
          UserIconView(user: user, iconSize: ImConstant.IM_USER_ICON_SIZE),
          Padding(
            padding: const EdgeInsets.only(left: 10),
            child: Column(
              children: [
                Text(
                  this.user.userName ?? '',
                  style: const TextStyle(fontSize: ImConstant.IM_DEFAULT_SIZE, fontFamily: "500"),
                ),
                Text(
                  this.user.motto ?? '',
                  style: const TextStyle(fontSize: ImConstant.IM_SMALL_SIZE),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildUserSetting() {
    return const ListTile(
      title: Text('设置备注和标签'),
      trailing: Icon(Icons.arrow_right),
    );
  }

  Widget _buildSendMessagePane(BuildContext context) {
    return SizedBox(
      height: 50,
      child: InkWell(
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.message_outlined),
            Text('发送消息'),
          ],
        ),
        onTap: () {
          _showSendMessage(context);
        },
      ),
    );
  }

  Widget _buildSendAudioPane(BuildContext context) {
    return SizedBox(
      height: 50,
      child: InkWell(
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.multitrack_audio_outlined),
            Text('音视频通话'),
          ],
        ),
        onTap:  () async {
          var sessionUserId = ImSingleton.getInstance().session.userId;
          if (sessionUserId == user.userId) {
            openDialog(context, '警告', const Text('不能与自己进行语音通信'), ()=>{});
            return;
          }
          var sessionDao = ImSessionDao();
          var session = await sessionDao.getByUserId(sessionUserId!, sessionUserId, user.userId);
          if (session == null) {
            session = ImSession.buildWithUser(sessionUserId, user);
            await sessionDao.insert(session);
          }
          var userSet = <ImUser>{};
          userSet.add(user);

          if (context.mounted) {
            showVideoAndAudioBottomSheet(context, session);
          }
        },
      ),
    );
  }

  void _showSendMessage(BuildContext context) async {
    var userId = ImSingleton.getInstance().session.userId;
    ImSession imSession;

    var sessionDao = ImSessionDao();
    var session = await sessionDao.getByUserId(userId!, userId, user.userId);
    if (session == null) {
      imSession = ImSession.buildWithUser(userId, user);
      imSession.status = ImSessionStatus.enable;
      await sessionDao.insert(imSession);
    } else {
      session.updateTime = DateTime.now();
      await sessionDao.batchUpdates(userId, [session!]);
      imSession = session;
    }

    if (context.mounted) {
      SessionListCubit sessionListCubit = context.read<SessionListCubit>();
      sessionListCubit.addSession(imSession);
      Navigator.of(context).pushNamedAndRemoveUntil("/MessageSendPage", ModalRoute.withName('/MainPage'), arguments: {"id": imSession?.id!, "name": imSession?.name});
    }
  }
}
